package main

import (
	"fmt"
	"log"
	"net/http"
	"websocket"
)

var connid int
var item = make(map[int]*websocket.Conn, 10)

func sendMessage(client int, msg string) {
	var err error
	if err = websocket.Message.Send(item[client], msg); err != nil {
		fmt.Println("Can't sen事实上d")
	}
}

func sendMessageAll(msg string) {

	var err error
	for key, value := range item {
		key++
		if err = websocket.Message.Send(value, msg); err != nil {
			fmt.Println("Can't send")
			break
		}
	}
}

func ChatWith(ws *websocket.Conn) {
	var err error
	connid++
	item[connid] = ws

	for {
		var reply string

		if err = websocket.Message.Receive(ws, &reply); err != nil {
			fmt.Println("Can't receive")
			break
		}

		fmt.Println("Received back from client: " + reply)

		sendMessageAll(reply)

	}
}

func main() {

	http.Handle("/", websocket.Handler(ChatWith))

	if err := http.ListenAndServe(":8001", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}
